package com.study.system.user.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.common.entity.User;
import com.edu.common.entity.UserVO;
import com.edu.common.util.JwtUtils;
import com.edu.common.util.RsaUtils;
import com.study.system.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获得登录的用户
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        //查询用户详细信息
        User user1 = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername,user.getUsername()));
        //将用户信息转换为jwt字符串
        String token = JwtUtils.generateUserToken(user1, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        //将用户信息返回给前端
        response.addHeader("Content-Type","application/json;charset=UTF-8");
        UserVO userVO = new UserVO(token,user1);
        response.getWriter().write(JSON.toJSONString(ResponseEntity.ok(userVO)));
    }
}
